/***********************************************************
* 
*     File Name:  taskWork.cpp
* 
*        Author:  Algolc
* 
*          mail:  17360224@qq.com
* 
*  Created Time:  Wed 11 Jul 2018 03:35:29 PM CST
* 
***********************************************************/
#include "zhelpers.h"
int main() {
    void* context = zmq_ctx_new();
    assert(context);

    //用于接受消息的套接字
    void* recevier = zmq_socket(context, ZMQ_PULL);
    int ret = zmq_connect(recevier, "tcp://localhost:5557");
    assert(!ret);

    //消息发往的套接字
    void* sender = zmq_socket(context, ZMQ_PUSH);
    ret = zmq_connect(sender, "tcp://localhost:5558");
    assert(!ret);
    
    //用于控制输入的套接字
    void* controller = zmq_socket(context, ZMQ_SUB);
    ret = zmq_connect(controller, "tcp://localhost:5559");
    assert(!ret);
    zmq_setsockopt(controller, ZMQ_SUBSCRIBE, "", 0);

    //处理来自接受者和控制器的消息
    zmq_pollitem_t items[] = {
        {recevier, 0, ZMQ_POLLIN, 0},
        {controller, 0, ZMQ_POLLIN, 0}
    };

    while(1) {
        zmq_msg_t message;
        zmq_poll(items, 2, -1);
        if (items[0].revents & ZMQ_POLLIN) {
            zmq_msg_init(&message);
            zmq_msg_recv(&message, recevier, 0);
    
            //执行工作
            s_sleep(atoi((char*)zmq_msg_data(&message)));

            //发送结果到接受器
            zmq_msg_init(&message);
            zmq_msg_send(&message, sender, 0);

            //用于查看器的简易过程指示器
            printf(".");
            fflush(stdout);

            zmq_msg_close(&message);
        }

        if (items[1].revents & ZMQ_POLLIN) {
            break;
        }
    }

    zmq_close(recevier);
    zmq_close(sender);
    zmq_close(controller);
    zmq_ctx_destroy(context);

    return 0;
}
